package day02;

import java.util.concurrent.locks.ReentrantLock;

//Lock锁
public class Demo5 {
    //Lock锁：有排他锁的功能，也有公平锁和非公平锁的功能
    ReentrantLock lock=new ReentrantLock();
    public void test(){
        String name= null;
        try {
            name = Thread.currentThread().getName();
            lock.lock();//加锁
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            System.out.println(name+"开始执行");
            //为防止异常发生没有关闭，会写finally在里面
            lock.unlock();//释放锁
        }
        System.out.println(name+"结束执行");
    }

    public static void main(String[] args) {
        Demo5 d=new Demo5();
        new Thread(()->{
            d.test();
        },"张三").start();
        new Thread(()->{
            d.test();
        },"李四").start();
    }
}
